package com.spring.api.json;

import apijson.Log;
import apijson.framework.APIJSONApplication;
import apijson.framework.APIJSONCreator;
import apijson.orm.SQLConfig;
import apijson.orm.SQLExecutor;
import com.spring.api.json.config.DemoSQLConfig;
import com.spring.api.json.config.DemoSQLExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author liuzhiqiang
 */
@Configuration
@SpringBootApplication
@EnableConfigurationProperties
@Slf4j
public class ApiJoinApplication implements CommandLineRunner {

    // 全局 ApplicationContext 实例，方便 getBean 拿到 Spring/SpringBoot 注入的类实例
    private static ApplicationContext APPLICATION_CONTEXT;

    static {
        // 使用本项目的自定义处理类
        APIJSONApplication.DEFAULT_APIJSON_CREATOR = new APIJSONCreator<Long>() {
            @Override
            public SQLConfig createSQLConfig() {
                return new DemoSQLConfig();
            }

            @Override
            public SQLExecutor createSQLExecutor() {
                return new DemoSQLExecutor();
            }
        };
    }

    public static ApplicationContext getApplicationContext() {
        return APPLICATION_CONTEXT;
    }

    public static void main(String[] args) throws Exception {
        APPLICATION_CONTEXT = SpringApplication.run(ApiJoinApplication.class, args);

        Log.DEBUG = true;
        // 4.4.0 以上需要这句来保证以上 static 代码块中给 DEFAULT_APIJSON_CREATOR 赋值会生效
        APIJSONApplication.init(false);
    }

    // 支持 APIAuto 中 JavaScript 代码跨域请求
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOriginPatterns("*")
                        .allowedMethods("*")
                        .allowCredentials(true)
                        .maxAge(3600);
            }
        };
    }

    @Override
    public void run(String... args) {
        log.info("ApiJoinApplication服务器已启动完毕");
    }


}
